<template>
  <div class="category-page">
    <header class="header">
      <div class="container">
        <div class="logo">
          <h1>小米商城</h1>
        </div>
        <nav class="nav">
          <router-link to="/">首页</router-link>
          <router-link to="/products">商品</router-link>
        </nav>
      </div>
    </header>

    <div class="container">
      <h2 class="page-title" v-if="category">{{ category.name }}</h2>
      <div class="product-list">
        <div 
          v-for="product in products" 
          :key="product.id"
          class="product-item"
          @click="goToProduct(product.id)"
        >
          <div class="product-image">
            <img :src="product.image || '/placeholder.png'" :alt="product.name">
          </div>
          <div class="product-info">
            <h3>{{ product.name }}</h3>
            <p class="price">¥{{ product.price }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '../utils/request'

const route = useRoute()
const router = useRouter()
const products = ref([])
const category = ref(null)

const goToProduct = (id) => {
  router.push(`/products/${id}`)
}

onMounted(async () => {
  try {
    const [categoryRes, productsRes] = await Promise.all([
      request.get(`/categories/${route.params.id}`),
      request.get('/products')
    ])
    category.value = categoryRes.data
    // 过滤该分类下的商品
    products.value = (productsRes.data || []).filter(
      p => p.category_id == route.params.id
    )
  } catch (error) {
    console.error('加载数据失败:', error)
  }
})
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 15px 0;
  margin-bottom: 40px;
}

.header .container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo h1 {
  color: #E02E24;
  font-size: 24px;
}

.nav {
  display: flex;
  gap: 30px;
}

.nav a {
  text-decoration: none;
  color: #333;
}

.page-title {
  font-size: 32px;
  margin-bottom: 40px;
}

.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 30px;
}

.product-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.product-image {
  width: 100%;
  height: 200px;
  background: #f5f5f5;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 20px;
}

.product-info h3 {
  font-size: 16px;
  margin-bottom: 10px;
}

.price {
  color: #E02E24;
  font-size: 20px;
  font-weight: bold;
}
</style>

